import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/elder_time_line_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/pending_group_page.dart';
import 'package:ls_work/a_yyt/widget/client_time_cell.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';

import '../../util/flat_button.dart';



///评估分配
class PendingBizType1002 extends StatefulWidget {
  final WaitingRighInfo? info;
  final VoidCallback? callBack;
  PendingBizType1002({Key? key, this.info, this.callBack});
  @override
  _PendingBizType1002State createState() => _PendingBizType1002State();
}

class _PendingBizType1002State extends State<PendingBizType1002> {
  List<TimeLinesInfo> timeLineList = [];
  List<List<PendingSelectedGroupEntity>> _groupList = [];
  List<PendingSelectedGroupEntity> _staffList = [];

  int currentIndex = 0;
  String groupName = '';
  String staffName = '';
  String allocationType = '';
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fectElderTimeLine();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('评估分配'),
        elevation: 0.5,
      ),
      body: Container(
        height: ScreenUtil.getScreenH(context),
        width: ScreenUtil.getScreenW(context),
        padding: EdgeInsets.fromLTRB(30, 30, 30, 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '   长者：',
                style: TextStyles.textGray18,
              ),
              TextSpan(
                text: '${widget.info?.elderName ?? ''}',
                style: TextStyles.textDark18,
              ),
            ])),
            Gaps.vGap16,
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '   评估类型：',
                style: TextStyles.textGray18,
              ),
              TextSpan(
                text: '${widget.info?.bizParams?.serviceItem ?? ''}',
                style: TextStyles.textDark18,
              ),
            ])),
            ClickItem(
              title: '*分配类型：',
              titleStyle: TextStyles.textGray18,
              content: '$allocationType',
              onTap: () {
                AppNavigator.push(
                  context,
                  PendingGroupPage(
                    callBack: (groupList, staffList, index) {
                      _groupList = groupList;
                      _staffList = staffList;
                      if (index == 0) {
                        ///分配到组
                        // setState(() {
                        for (var item in groupList) {
                          for (var item2 in item) {
                            if (item2.isSelected==true) {
                              groupName += '${item2.name}，';
                            }
                          }
                        }
                        // });
                      } else {
                        ///分配到人
                        // setState(() {
                        for (var item in staffList) {
                          for (var item2 in (item.user??<PendingSelectedGroupInfo>[])) {
                            if (item2.isSelected==true) {
                              staffName = item2.userName??"";
                            }
                          }
                        }
                        // });
                      }
                      print(staffName);
                      print(groupName);
                      if (!TextUtil.isEmpty(groupName) ||
                          !TextUtil.isEmpty(staffName)) {
                        setState(() {
                          currentIndex = index;
                          allocationType = index == 0 ? '分配到组' : '分配到人';
                        });
                      }
                    },
                  ),
                );
              },
            ),
            Gaps.vGap16,
            currentIndex != null
                ? Text.rich(TextSpan(children: [
                    TextSpan(
                      text: currentIndex == 0 ? '   分配到组：' : '   分配到人：',
                      style: TextStyles.textGray18,
                    ),
                    TextSpan(
                      text: currentIndex == 0 ? groupName : staffName,
                      style: TextStyles.textDark18,
                    ),
                  ]))
                : Container(),
            Gaps.vGap50,
            Gaps.line,
            Expanded(
              child: ListView.builder(
                itemCount: timeLineList.length,
                itemBuilder: (_, index) {
                  return ClientTimeCell(
                    count: timeLineList.length,
                    info: timeLineList[index],
                  );
                },
              ),
            ),
            SizedBox(
              width: ScreenUtil.getScreenW(context),
              height: 50,
              child: FlatsButton(
                color: Colors.blue,
                highlightColor: Colors.blue[700]!,
                child: Text("提交"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0)),
                onPressed: _send,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void fectElderTimeLine() {
    var map = {
      'traceType': 130,
      'relationId': widget.info?.bizId,
      'customerId': widget.info?.customerId,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.elderTimeLine, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            TimeLineEntity model = TimeLineEntity.fromJson(map['data']);
            // print('🍎 - length - ${model.rows.length}');
            if ((model.rows??[]).length >= 0) {
              setState(() {
                timeLineList = model.rows??[];
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///提交
  void _send() {
    if (currentIndex == null) {
      Toast.show('请选择分配类型');
      return;
    }
    var tempList = [];
    if (currentIndex == 0) {
      ///分组
      for (var item in _groupList) {
        for (var item2 in item) {
          if (item2.isSelected==true) {
            var dic = {
              'serviceGroupId': item2.id,
            };
            tempList.add(dic);
          }
        }
      }
    } else {
      for (var item in _staffList) {
        for (var item2 in (item.user??<PendingSelectedGroupInfo>[])) {
          if (item2.isSelected==true) {
            var dic = {
              'serviceGroupId': item2.serviceGroupId,
              'ownerId': item2.userId,
            };
            tempList.add(dic);
          }
        }
      }
    }
    var map = {
      'assignType': currentIndex,
      'evaluationId': widget.info?.bizId,
      'assignToList': tempList,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.appAssign, data: map).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
